package test2;


import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.nio.charset.StandardCharsets;

/**
 * @author liule
 * @date 2023/8/7 14:37
 * @Desc :
 */
public class HttpClientTest3 {
    public static void main(String[] args) throws Exception {
        //可关闭的httpclient客户端，相当于你打开的一个浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String urlstr = "https://github.com/";
        HttpGet httpGet = new HttpGet(urlstr);
        // 创建一个代理
        String ip = "121.225.46.250"; //Caused by: java.net.ConnectException: Connection timed out: connect // 连接超时
        int port = 8080;
        HttpHost proxy = new HttpHost(ip);
        // 对每一个请求进行配置，会覆盖全局的默认请求配置
        RequestConfig requestConfig = RequestConfig.custom()
//                .setProxy(proxy)
//                连接超时和读取超时
//                连接超时, ms,完成tcp3次握手的时间上线
                .setConnectTimeout(5000)
//                读取超时,ms, 表示从请求的网址获取响应数据的时间间隔
                .setSocketTimeout(3000)
                // 指的从连接池里面获取connection的超时时间
                .setConnectionRequestTimeout(5000)
                .build();
        httpGet.setConfig(requestConfig);

        // 可关闭的响应
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpGet);
            // 代表本次请求的成功失败的状态
            StatusLine statusLine = response.getStatusLine();
            if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
                HttpEntity entity = response.getEntity();
                String toStringSesult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStringSesult);
                EntityUtils.consume(entity); // 确保流关闭
            } else {
                System.out.println("响应失败，响应码：" + statusLine.getStatusCode());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }

    }
}
